package com.wxy.livebroadcast.scheduling;

import com.wxy.livebroadcast.service.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.IOException;
import java.time.Instant;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author: wengxinyou
 * @Email: wengxinyou@wintelia.com
 * @Date: 2022/4/23 23:39
 * @Describe:
 */
@Configuration
@EnableScheduling
@Slf4j
public class HeartBeatTask
{
    @Scheduled(cron="0/3 * * * * ?")
    private void configureTasks()
            throws IOException
    {
        Map<WebSocketServer, Instant> map = WebSocketServer.getUserMap();
        Set<Map.Entry<WebSocketServer, Instant>> users = map.entrySet();
        for (Map.Entry<WebSocketServer, Instant> user : users)
        {
            Instant value = (Instant)user.getValue();
            WebSocketServer key = (WebSocketServer)user.getKey();
            Instant time = value.plusMillis(TimeUnit.SECONDS.toMillis(3L));
            Instant now = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8L));
            log.info("name = " + key.name + ", value = " + value + ", 3s after time = " + time + ", now = " + now);
            if (time.isBefore(now))
            {
                log.info("删除设备" + key.name);
                key.session.close();
            }
        }
    }
}
